package com.xiaochen.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.xiaochen.common.exception.XiaoChenException;
import com.xiaochen.model.dto.h5.UserLoginDto;
import com.xiaochen.model.dto.h5.UserRegisterDto;
import com.xiaochen.model.entity.user.UserInfo;
import com.xiaochen.model.vo.common.ResultCodeEnum;
import com.xiaochen.model.vo.h5.UserInfoVo;
import com.xiaochen.user.mapper.UserInfoMapper;
import com.xiaochen.user.service.UserInfoService;
import com.xiaochen.utils.AuthContextUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class UserInfoServiceImpl implements UserInfoService {

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;


    // 定义h5用户登录的token信息
    public final static String USER_LOGIN_TOKEN = "user:userLogin:";
    /**
     * 会员注册
     *
     * @param userRegisterDto
     */
    @Override
    public void register(UserRegisterDto userRegisterDto) {
        // 1.从userRegisterDto中获取数据
        String username = userRegisterDto.getUsername();
        String password = userRegisterDto.getPassword();
        String nickName = userRegisterDto.getNickName();
        String code = userRegisterDto.getCode();
        // 2.校验验证码
        String redisCode = redisTemplate.opsForValue().get(username);
        if (!code.equals(redisCode)){
            throw new XiaoChenException(ResultCodeEnum.VALIDATECODE_ERROR);
        }
        // 3.校验用户名
        UserInfo userInfo = userInfoMapper.selectByUsername(username);
        if (userInfo != null){
            throw new XiaoChenException(ResultCodeEnum.USER_NAME_IS_EXISTS);
        }
        // 4.封装数据,插入数据库
        // 因为在校验用户名的时候,已经将数据查询出来了——是null,所以在这里重新定义成一个UserInfo对象————————但是这样不推荐,可读性差
        // 可以像下面这样直接创建一个新的对象用来封装数据用来添加到数据库中
        UserInfo newUserInfo = new UserInfo();
        newUserInfo.setUsername(username);
        newUserInfo.setNickName(nickName);
        newUserInfo.setPassword(DigestUtils.md5DigestAsHex(password.getBytes()));
        newUserInfo.setPhone(username);
        newUserInfo.setStatus(1);
        newUserInfo.setSex(0);
        newUserInfo.setAvatar("http://thirdwx.qlogo.cn/mmopen/vi_32/DYAIOgq83eoj0hHXhgJNOTSOFsS4uZs8x1ConecaVOB8eIl115xmJZcT4oCicvia7wMEufibKtTLqiaJeanU2Lpg3w/132");

        userInfoMapper.save(newUserInfo);
        // 5.删除验证码(删除redis中的code)
        redisTemplate.delete(username);
    }

    /**
     * 登录
     * h5登录的账号密码
     * 账号:13886218394
     * 密码:11111111
     *
     * @param userLoginDto
     */
    @Override
    public String login(UserLoginDto userLoginDto) {
       // 1.验证用户输入的账号是否跟数据库中存在的一致
        UserInfo userInfo = userInfoMapper.selectByUsername(userLoginDto.getUsername());
        if(userInfo == null){
            throw new XiaoChenException(ResultCodeEnum.LOGIN_ERROR);
        }
        // 2.密码不一致-->抛出异常并返回,用MD5加密后对比
        String database_password = userInfo.getPassword();
        String input_password = userLoginDto.getPassword();
        if (database_password.equals(DigestUtils.md5DigestAsHex(input_password.getBytes()))){
            throw new XiaoChenException(ResultCodeEnum.LOGIN_ERROR);
        }
        // 校验用户是否禁用
        if (userInfo.getStatus() == 0){
            throw new XiaoChenException(ResultCodeEnum.ACCOUNT_STOP);
        }
        // 3.一致-->生成token
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        // 4.将token存在redis中
        redisTemplate.opsForValue().set(USER_LOGIN_TOKEN+token,
                                        JSON.toJSONString(userInfo),
                                        12,
                                        TimeUnit.HOURS);
        // 5.登录成功
        return token;
    }

    /**
     * 获取用户信息
     *
     * @param token
     * @return
     */
    @Override
    public UserInfoVo getCurrentUserInfo(String token) {
/*        // 根据token从redis中获取用户信息
        String userJson = redisTemplate.opsForValue().get(USER_LOGIN_TOKEN + token);
        if (!StringUtils.hasText(userJson)){
            throw new XiaoChenException(ResultCodeEnum.LOGIN_AUTH);
        }
        UserInfo userInfo = JSON.parseObject(userJson,UserInfo.class);*/

        // 从ThreadLocal中获取用户信息
        UserInfo userInfo = AuthContextUtil.getUserInfo();
        // 将userInfo转换成UserInfoVo
        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtils.copyProperties(userInfo,userInfoVo);
        return userInfoVo;
    }
}
